package com.gwtgeo.ui.client.defbuilder;

import java.util.List;

import org.gwtopenmaps.openlayers.client.Bounds;
import org.gwtopenmaps.openlayers.client.LonLat;
import org.gwtopenmaps.openlayers.client.Map;
import org.gwtopenmaps.openlayers.client.layer.WMS;

import com.gwtgeo.service.model.MapDef;

public class MapDefBuilder implements DefBuilder<MapDef, Map> {

	public static final String NUM_ZOOM_LEVELS = "NUM_ZOOM_LEVELS";
	public static final String ZOOM = "ZOOM";
	public static final String HEIGHT = "HEIGHT";
	public static final String WIDTH = "WIDTH";
	public static final String MAP = "MAP";
	public static final String LAYERS = "LAYERS";
	public static final String LOCATIONS = "LOCATIONS";
	
	@Override
	public MapDef buildDef(Map viewObj, java.util.Map<String, Object> params) {

		MapDef def = new MapDef();

		Integer numZoomLevels = (Integer) params.get(NUM_ZOOM_LEVELS);
		def.setNumZoomLevels(numZoomLevels);
		def.setProjection(viewObj.getProjection());
		Bounds bounds = viewObj.getExtent();
		def.setLowerLeftX(bounds.getLowerLeftX());
		def.setLowerLeftY(bounds.getLowerLeftY());
		def.setUpperRightX(bounds.getUpperRightX());
		def.setUpperRightY(bounds.getUpperRightY());
		def.setCenterXCoordinate(viewObj.getCenter().lat());
		def.setCenterYCoordinate(viewObj.getCenter().lon());
		String height = (String) params.get(HEIGHT);
		def.setHeight(height);
		String width = (String) params.get(WIDTH);
		def.setWidth(width);
		Integer zoom = (Integer) params.get(ZOOM);
		def.setZoom(zoom);

		return def;
	}

	@Override
	@SuppressWarnings("unchecked")
	public Map buildObj(MapDef def, java.util.Map<String, Object> params) {

		Map map = (Map) params.get(MAP);

		LonLat center = new LonLat(def.getCenterYCoordinate(), def
				.getCenterXCoordinate());
		map.setCenter(center, def.getZoom());
		
		Bounds bounds = new Bounds(def.getLowerLeftX(), def.getLowerLeftY(),
				def.getUpperRightX(), def.getUpperRightY());
		map.zoomToExtent(bounds);

		map.removeOverlayLayers();
		List<WMS> layers = (List<WMS>) params.get(LAYERS);
		for (WMS wms : layers) {
			map.addLayer(wms);
		}

		return map;
	}

}
